package com.lagou;

/**
 * @author HuanyuZhou
 * @date 2020/12/15 16:12
 */
public class DeadLock {
    //共享资源1
    public String lock1 = "lock1";
    //共享资源2
    public String lock2 = "lock2";
    public static void main(String[] args) {
        final DeadLock deadLock = new DeadLock();
        Thread thread = new Thread(new Runnable() {
            @Override
            public void run() {
                //先占有共享资源1
                synchronized (deadLock.lock1){
                    try {
                        //等待线程2持有共享资源2
                        System.out.println(Thread.currentThread().getName()+"锁住了lock1");
                        Thread.sleep(2000);
                        //尝试持有共享资源2
                        synchronized (deadLock.lock2){
                            System.out.println("锁住了lock2");
                        }
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        });

        Thread thread2 = new Thread(new Runnable() {
            @Override
            public void run() {
                //先占有共享资源2
                synchronized (deadLock.lock2){
                    try {
                        //等待线程1持有共享资源1
                        System.out.println(Thread.currentThread().getName()+"锁住了lock2");
                        Thread.sleep(2000);
                        //尝试持有共享资源1
                        synchronized (deadLock.lock1){
                            System.out.println("锁住了lock1");
                        }
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        });

        thread.start();
        thread2.start();
    }
}
